package net.maku.system.controller;

import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.maku.constant.SystemConstant;
import net.maku.framework.common.utils.DateUtils;
import net.maku.framework.common.utils.FileConvertUtil;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.common.utils.Result;
import net.maku.system.query.SysLogOperateQuery;
import net.maku.system.service.SysLogOperateService;
import net.maku.system.vo.SysLogOperateVO;
import net.maku.utils.BeansUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 操作日志
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("sys/log/operate")
@Tag(name = "操作日志")
@AllArgsConstructor
@Slf4j
public class SysLogOperateController {
    private final SysLogOperateService sysLogOperateService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @PreAuthorize("hasAuthority('sys:operate:all')")
    public Result<PageResult<SysLogOperateVO>> page(@ParameterObject @Valid SysLogOperateQuery query) {
        PageResult<SysLogOperateVO> page = sysLogOperateService.page(query);

        return Result.ok(page);
    }

    @GetMapping(value = "/downloadZip/**")
    @Operation(summary = "下载日志文件")
    @PreAuthorize("hasAuthority('sys:logFile:download')")
    public void downloadZip(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 文件名称（子路径）
        String subPath = URLDecoder.decode(request.getRequestURI(), "UTF-8").replaceFirst("^/sys/log/operate/downloadZip", "");
        //获取文件名称
        String fileName = new File(subPath).getName();
        String path = BeansUtils.SysParamsCache.get(SystemConstant.key_name_system_log_path) + subPath;
        Map map = Maps.newHashMap();
        map.put("name", fileName);
        map.put("path", path);
        FileConvertUtil.zipDirFileToFile(Arrays.asList(map), request, response);
    }

    @GetMapping(value = "/file/list")
    @Operation(summary = "日志文件列表")
    @PreAuthorize("hasAuthority('sys:logFile:list')")
    public Result<PageResult<Map>> downloadZipList(HttpServletRequest request, HttpServletResponse response) {
        String path = BeansUtils.SysParamsCache.get(SystemConstant.key_name_system_log_path);
        List list = FileConvertUtil.getListFiles(path).stream().sorted(Comparator.comparing(File::lastModified, Comparator.reverseOrder())).map((p -> {
            Map map = new HashMap<>();
            // 使用正则表达式替换匹配的部分为空字符串
            String result = p.getParent().replaceFirst("^" + path, "");
            map.put("fileName", result + File.separator + p.getName());

            long fileSizeInBytes = p.length();
            double fileSize;
            String unit;
            if (fileSizeInBytes < 1024 * 1024) {
                fileSize = (double) fileSizeInBytes / 1024; // 使用KB
                unit = "KB";
            } else {
                fileSize = (double) fileSizeInBytes / (1024 * 1024); // 使用MB
                unit = "MB";
            }
            // 格式化文件大小为两位小数
            DecimalFormat decimalFormat = new DecimalFormat("#0.00");
            String formattedFileSize = decimalFormat.format(fileSize);
            map.put("fileSize",formattedFileSize + " " + unit);

            long lastModifiedTimestamp = p.lastModified();
            Date lastModifiedDate = new Date(lastModifiedTimestamp);
            String formattedDate =DateUtils.format(lastModifiedDate, DateUtils.DATE_TIME_PATTERN);
            map.put("lastModifiedDate",formattedDate);

            return map;
        })).collect(Collectors.toList());
        PageResult<Map> page = new PageResult<>(list, list.size());
        return Result.ok(page);
    }

    @ResponseBody
    @RequestMapping("/app/v1/print")
    void echoAppLog(String content) {
        log.info("源自APP的操作：{}", content);
    }

    @ResponseBody
    @RequestMapping("/app/v1/prints")
    void echoAppLog(String[] contents) {
        for (String item : contents) {
            log.info("源自APP的操作：{}", item);
        }
    }
}
